package com.enniswu.weitter.network;

import android.Manifest;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.util.Log;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class HttpClient {

    private static volatile HttpClient instance;
    private OkHttpClient client;

    private HttpClient() {
        client = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.MINUTES)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    public synchronized static HttpClient getInstance() {
        if (instance == null) {
            synchronized (HttpClient.class) {
                if (instance == null) {
                    instance = new HttpClient();
                }
            }
        }
        return instance;
    }

    @RequiresPermission(Manifest.permission.INTERNET)
    public void post(@Nullable String sessionId, String url, Map<String, String> params,
                     Callback callback) {
        Request.Builder builder = new Request.Builder()
                .url(url)
                .post(buildBody(params));
        if (sessionId != null)
            builder.addHeader("cookie", sessionId);
        Log.d("url", url);
        client.newCall(builder.build()).enqueue(callback);
    }

    @RequiresPermission(Manifest.permission.INTERNET)
    public void post(String sessionId, String url, Map<String, String> params,
                     String fileKey, List<File> files, Callback callback) {
        Request request = new Request.Builder()
                .addHeader("cookie", sessionId)
                .url(url)
                .post(buildBody(params, fileKey, files))
                .build();
        Log.d("url", url);
        client.newCall(request).enqueue(callback);
    }

    private RequestBody buildBody(Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        StringBuilder param = new StringBuilder("[");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
            param.append(entry.getKey()).append(':').append(entry.getValue()).append(',');
        }
        param.append(']');
        RequestBody body = builder.build();
        param.append(',').append("body").append(body);
        Log.d("请求", param.toString());
        return body;
    }

    private RequestBody buildBody(Map<String, String> params, String fileKey, List<File> files) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        StringBuilder param = new StringBuilder("[");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
            param.append(entry.getKey()).append(':').append(entry.getValue()).append(',');
        }
        for (File file : files) {
            builder.addFormDataPart(fileKey, file.getName(),
                    RequestBody.create(MediaType.parse("application/octet-stream"), file));
        }
        param.append(']');
        RequestBody body = builder.build();
        param.append(',').append("body").append(body);
        Log.d("带文件请求", param.toString());
        return body;
    }

    public static String getFailMessage() {
        return getMessage(100);
    }

    public static String getErrorMessage() {
        return getMessage(101);
    }

    public static String getMessage(int code) {
        switch (code) {
            case 101:return "请求错误";
            case 100:return "连接失败，请检查网络设置";

            default:return "未知错误";
        }
    }

    public static class URLStore {
        private static final String HOST = "http://193.112.26.227:9800/";

        public static final String LOGIN = HOST + "user/login";
        public static final String REGISTER = HOST + "user/register";
        public static final String LOGOUT = HOST + "user/logout";

        public static final String USER_INFO_SIMPLE = HOST + "person/simpleInfo";
        public static final String USER_INFO_UPDATE = HOST + "person/changeInfo";
        public static final String USER_INFO_GET = HOST + "person/getInfo";

        public static final String SEARCH_PHONE = HOST + "search/userByPhone";
        public static final String SEARCH_NAME = HOST + "search/usersByName";

        public static final String CODE_SEND = HOST + "user/authPhone";
        public static final String CODE_AUTH = HOST + "user/authSuccess";

        public static final String FOLLOWING_ADD = HOST + "like/add";
        public static final String FOLLOWING_REMOVE = HOST + "like/delete";
        public static final String FOLLOWING_GET = HOST + "like/get";
        public static final String FOLLOWS_GET = HOST + "like/follow";

        public static final String UPLOAD_IMAGE = HOST + "image/upload";
        public static final String UPLOAD_ALBUM = HOST + "album/upload";
        public static final String DOWNLOAD_IMAGE = HOST + "image/download";
        public static final String DOWNLOAD_ALBUM = HOST + "album/download";

        public static final String POST_ADD = HOST + "post/add";
        public static final String POST_DELETE = HOST + "post/delete";
        public static final String POST_GET = HOST + "post/get";

        public static final String POST_LIST_USER = HOST + "post/getByUser";
        public static final String POST_LIST_PUBLIC = HOST + "search/postsByType";
        public static final String POST_LIST_COMMENT = HOST + "post/getByPost";
    }
}
